<template>
  <div class="app-container">
    <div class="app-container_conter">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="被保险人" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入被保险人" clearable size="small"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="保单号码" prop="insure_no">
        <el-input v-model="queryParams.insure_no" placeholder="请输入保单号码" clearable size="small"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="时间" prop="timeData">
        <el-date-picker
            v-model="queryParams.timeData"
            type="daterange"
            range-separator="-"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button style="background: #00afff;color: #FFFFFF"   size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="info" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    <el-row :gutter="10" class="mb8">-->

    <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    <!--    </el-row>-->
<!--
              :row-class-name="tableRowClassName"
              @row-click="clickRow"
              ref="multipleTable"
              @select="handleSelect"-->
    <el-table v-loading="loading" :data="insureEliList"
              @selection-change="handleSelectionChange"
              :header-cell-style="tableHeaderColor"

    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="保单号" align="center" prop="insure_no" fixed min-width="180px"/>
      <el-table-column label="上级用户" align="center" prop="create_by" min-width="120px"/>
      <el-table-column label="保险公司/产品" align="center" prop="insure_name" min-width="250px"/>
      <el-table-column label="被保险人" align="center" prop="name2" min-width="150px"/>

      <!--      <el-table-column label="总保险费" align="center" prop="sinsurance_fee_count" />-->
      <el-table-column label="保险起期" align="center" min-width="130px" prop="insurance_time_start"/>
      <el-table-column label="保险止期" align="center" min-width="130px" prop="insurance_time_end"/>
      <el-table-column label="创建时间" align="center" min-width="130px" prop="create_time"/>
      <el-table-column label="操作" align="center" fixed="right" min-width="120px" class-name="small-padding fixed-width"
                       width="250px">
        <template slot-scope="scope">
          <el-button
              icon="el-icon-upload2"
              size="mini"
              type="text"
              v-hasPermi="['insurance:approveLog:add']"
              @click="handleApprove(scope.row)"
          >批单
          </el-button>
          <el-button
              icon="el-icon-s-custom"
              size="mini"
              type="text"
              v-hasPermi="['insurance:approveLog:detail']"
              @click="getEdorsement(scope.row)"
          >查看批单
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    </div>

    <pagination
       style="background: transparent"
        v-show=" total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <el-dialog :title="upload.title" :visible.sync="upload.open1" width="650px" append-to-body style="margin: 0 auto">
      <!--       accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"-->
      <el-upload
          ref="upload"
          class="upload-demo"
          action :limit="1"
          :on-exceed="formHandleExceed"
          :file-list="formFileList"
          :on-remove="formHandleRemove"
          :http-request="handleUpdateForm"
          :before-upload="beforeUploadForm"
          :auto-upload="false"
          drag
      >

<!--        <i class="el-icon-upload"></i>-->
        <img src="../../../assets/images/Import.png" style="width: 83px;height: 91px;margin: 50px 0;"/>
        <div class="el-upload__text" >
       将文件拖到此处,或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="display: flex;justify-content: space-between;width: 600px" slot="tip">
          <div class="el-upload__tip" style="color:red" slot="tip">仅允许导入“xls”或“xlsx”格式文件！</div>
          <span style="display: inline-block;width: 250px"></span>
          <el-link type="info" style="font-size:12px;color: #31A5F8" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button style="background:#F1F1F1 " @click="upload.open1 = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {examines_single, importTemolate1} from "@/api/insurance/user";
import {get_insure} from "@/api/insurance/approveLog";

export default {
  name: "index",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 雇主责任险保单表格数据
      insureEliList: [],
      formFileList: [],//显示上传文件
      uploadFormFileList: [],//确定上传文件
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open1: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否更新已经存在的用户数据
        isSupportUpdate: false,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,//页码
        pageSize: 10,//每页数量
        insure_no: null,//保单号
        name: null,//投保人
        type: 2,
        timeData: [],//时间
        user_id: '',
        role_id: '',
      },

      //  保单id:
      insureId: '',
      user_id: '',//操作人id
    };
  },

  created() {
    var user = JSON.parse(localStorage.getItem('userInfo'));
    this.queryParams.user_id = user.userId;
    if (user.roles.length != 0) {
      this.queryParams.role_id = user.roles[0].roleId
    }
    this.user_id = JSON.parse(localStorage.getItem('userInfo')).userId;
    this.getList();

  },
  methods: {
    /* 修改表头颜色 */
    tableHeaderColor({ rowIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #304156;color: #fff;font-weight: 400;font-family: Microsoft YaHei;'
      }
    },
    handleApprove(row) {
      // console.log('row', row)
      this.formFileList = [];
      this.insureId = row.id
      this.upload.title = "添加批单";
      this.upload.open1 = true;

    },

// 选中背景色
//     tableRowClassName({ row }) {
//       // 选中背景色
//         return row.className;
//     },

// 点击整行选中
//     clickRow(row, event, column) {
//       if (row.className === "normal") {
//         row.className = "tableSelectedRowBgColor";
//       } else {
//         row.className = "normal";
//       }
//       this.$refs.multipleTable.toggleRowSelection(row);
//     },
    // 手动点击勾选框触发的事件
    // handleSelect(selection, row) {
    //   // selection,row  传递两个参数，row直接是对象
    //   // 只传一个参数得到的是数组
    //   if (row.className === "normal") {
    //     row.className = "tableSelectedRowBgColor";
    //   } else {
    //     row.className = "normal";
    //   }
    // },

    // 下载文件
    importTemplate() {
      var obj = {
        type: '1'
      }
      importTemolate1(obj).then(res => {
        // console.log('下载模板', res)
        if (res.code == 1) {
          let link = document.createElement('a'); // 创建a标签
          link.style.display = 'none';
          let objectUrl = res.data;
          link.href = objectUrl;
          link.click();
        }

      })
      // importTemolate(obj).then(res=>{
      //   this.download(res.msg);
      // })
    },
    //上传导入确定按钮
    submitFileForm() {
      this.$refs.upload.submit();
      // this.$refs.upload.submit();
    },
    //开始上传前验证
    beforeUploadForm(file) {
      // console.log('验证', file)
      //文件大小验证
      if (file.size / 1024 / 1024 > this.formMaxSize) {
        this.$message({
          message: `上传文件大小不能超过${this.formMaxSize}M!`,
          type: 'waning'
        })
        false
      }
      //  中文乱码处理
      if (file.raw) {
        let reader = new FileReader()//读取文件内容
        reader.readAsText(file.raw, 'gb2312')//防止中文乱码问题，不加reader.onload方法都不会触发
        reader.onload = function (e) {
          this.contentHtml = e.target.result;//txt文本内容，接下来就可以对其进行校验处理了
          // console.log('contentHtml', this.contentHtml);
        }
      }
      //验证文件类型
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'csv' || testmsg === 'XLS' || testmsg === 'XLSX'
      if (!extension) {
        this.$message({
          message: '上传文件只能是xlsx/xls/csv/XLS/XLSX格式',
          type: 'warning'
        })
      }
      return extension
    },
    //移除上传列表中的文件
    formHandleRemove(file, formFileList) {
      let that = this;
      for (let i = 0; i < that.uploadFormFileList.length; i++) {
        if (that.uploadFormFileList[i].pname === file.name) {
          that.uploadFormFileList.splice(i, 1);
          break;
        }
      }
    },
    // 允许上传文件个数验证
    formHandleExceed(files, formFileList) {
      // console.log('files', files)
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + formFileList.length} 个文件`)
    },
    //上传文件
    handleUpdateForm(param) {
      // console.log('param', param)
      // console.log('isSupportUpdate',this.upload)
      let that = this;
      let formData = new FormData();
      // console.log('id', that.insureId)
      // formData.append('id', that.form.insureId)//额外参数
      formData.append('excel', param.file);
      formData.append('insure_id', that.insureId);
      formData.append('user_id', that.user_id)
      // formData.append('isSupportUpdate',that.upload.isSupportUpdate)
      // console.log('param', formData);
      const loading = that.$loading({
        lock: true,
        text: '请耐心等待正在上传数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      examines_single(formData).then(response => {
        // console.log('res2356', response);
        loading.close();
        var that = this;
        if (response.code == 1) {

          that.$confirm(response.msg, '标题名称', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            callback: action => {
              if (response.data.length == 0) {
                this.upload.open1 = false;
              } else {
                setTimeout(()=>{
                  that.$confirm('是否要将添加用户部分错误的信息导出', '标题名称', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    callback: action => {
                      if (action == 'confirm') {
                        let link = document.createElement('a'); // 创建a标签
                        link.style.display = 'none';
                        let objectUrl = response.data;
                        link.href = objectUrl;
                        link.click();
                        this.upload.open1 = false;
                      }
                    }
                  });
                },500)
              }
            }
          });
        }

      })
    },

    /** 查询雇主责任险保单列表 */
    getList() {
      this.loading = true;
      get_insure(this.queryParams).then(response => {
        // console.log('查询', response)
        this.insureEliList = response.data.list;
        // this.insureEliList.forEach(v=>{
        //   v.className="normal"
        // })
        // console.log('insureEliList', this.insureEliList)
        this.total = response.data.count;
        this.loading = false;
      })
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      // if (selection.length > 0) {
      //   selection.forEach((item) => {
      //     if (item.className === "normal") {
      //       item.className = "tableSelectedRowBgColor";
      //     }
      //   });
      // } else {
      //   // 空数组初始化className
      //   this.insureEliList.forEach((item) => {
      //     if (item.className === "tableSelectedRowBgColor") {
      //       item.className = "normal";
      //     }
      //   });
      // }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: '/insureEli/add/'

      })
    },
    //点击查看批单跳转到批单页面
    getEdorsement(item) {
      this.$router.push({
        path: '/insurancemanagement/EndorsementPage/index',
        query: {
          Endorsement: item
        }
      })
    }
  }
}
</script>

<style lang="scss" >
.app-container{



}

</style>
